// 本地存储工具类
export class Storage {
  private prefix: string

  constructor(prefix: string = 'vue-base') {
    this.prefix = prefix
  }

  private getKey(key: string): string {
    return `${this.prefix}-${key}`
  }

  set(key: string, value: any): void {
    try {
      const serializedValue = JSON.stringify(value)
      localStorage.setItem(this.getKey(key), serializedValue)
    } catch (error) {
      console.error('存储数据失败:', error)
    }
  }

  get<T>(key: string, defaultValue?: T): T | null {
    try {
      const item = localStorage.getItem(this.getKey(key))
      if (item === null) return defaultValue || null
      return JSON.parse(item)
    } catch (error) {
      console.error('读取数据失败:', error)
      return defaultValue || null
    }
  }

  remove(key: string): void {
    localStorage.removeItem(this.getKey(key))
  }

  clear(): void {
    const keys = Object.keys(localStorage)
    keys.forEach(key => {
      if (key.startsWith(this.prefix)) {
        localStorage.removeItem(key)
      }
    })
  }
}

// 会话存储工具类
export class SessionStorageUtil {
  private prefix: string

  constructor(prefix: string = 'vue-base') {
    this.prefix = prefix
  }

  private getKey(key: string): string {
    return `${this.prefix}-${key}`
  }

  set(key: string, value: any): void {
    try {
      const serializedValue = JSON.stringify(value)
      window.sessionStorage.setItem(this.getKey(key), serializedValue)
    } catch (error) {
      console.error('存储数据失败:', error)
    }
  }

  get<T>(key: string, defaultValue?: T): T | null {
    try {
      const item = window.sessionStorage.getItem(this.getKey(key))
      if (item === null) return defaultValue || null
      return JSON.parse(item)
    } catch (error) {
      console.error('读取数据失败:', error)
      return defaultValue || null
    }
  }

  remove(key: string): void {
    window.sessionStorage.removeItem(this.getKey(key))
  }

  clear(): void {
    const keys = Object.keys(window.sessionStorage)
    keys.forEach(key => {
      if (key.startsWith(this.prefix)) {
        window.sessionStorage.removeItem(key)
      }
    })
  }
}

// 创建默认实例
export const storage = new Storage()
export const sessionStorage = new SessionStorageUtil() 